package com.renrenyou.duanshipin.util;

import android.util.Base64;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.renrenyou.duanshipin.net.Constance;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    public static String decodeString(String base64Data) {
        if (base64Data == null || base64Data.isEmpty()) {
            return null;
        }
        byte[] decodedBytes = Base64.decode(base64Data, Base64.DEFAULT);
        SecretKeySpec keySpec = new SecretKeySpec(Constance.AES_KE.getBytes(), "AES");
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        } catch (NoSuchAlgorithmException e) {
            Log.d("AESUtil", "decodeString11: " + e.getMessage());
        } catch (NoSuchPaddingException e) {
            Log.d("AESUtil", "decodeString22: " + e.getMessage());
        } catch (InvalidKeyException e) {
            Log.d("AESUtil", "decodeString33: " + e.getMessage());
        } catch (BadPaddingException e) {
            Log.d("AESUtil", "decodeString44: " + e.getMessage());
        } catch (IllegalBlockSizeException e) {
            Log.d("AESUtil", "decodeString55: " + e.getMessage());
        }
        return null;
    }

    public static boolean isJson(String data) {
        try {
            new Gson().fromJson(data, Object.class);
            return true;
        } catch (JsonSyntaxException e) {
            return false;
        }
    }
}
